// IIFE
(function(){

    // 小计
    const SubTotal = {
        props: {
            price: Number,
            amount: Number
        },
        template: `<span class="sub-total">
                      {{ price * amount }}
                   </span>`
    }

    // 购物车项
    const CartItem = {
        props: {
            ordinal: Number,
            name: String,
            price: Number,
            amount: Number
        },
        components: {
            SubTotal // 等同于 `SubTotal: SubTotal`
        },
        template: `<div class="cart-item">
                       <span class="ordinal">{{ ordinal }}</span>
                       <span class="name">{{ name }}</span>
                       <span class="price">{{ price.toFixed(2) }}元</span>
                       <span class="amount">{{ amount }}</span>
                       <SubTotal :price="price" :amount="amount"></SubTotal>
                   </div>`
    }

    // 总价格
    const Total = {
        props: {
            goods: Array
        },
        computed: {
            totalPrice() {
                return this.goods.reduce( (prev,curr) => prev + curr.price * curr.amount, 0);
            }
        },
        template: `<div class="total">
                      <span>{{totalPrice}}</span>
                   </div>`
    }

    // 购物车
    const ShoppingCart = {
        props: {
            goods: Array
        },
        components: {
            CartItem, // 等同于 `CartItem: CartItem`
            Total // 等同于 `Total: Total`
        },
        template: `<div class="shopping-cart">
                      <h3>购物车</h3>
                      <CartItem v-for="(g,index) in goods" 
                                :ordinal="index+1"
                                :name="g.name"
                                :price="g.price"
                                :amount="g.amount"
                                :key="g.id">
                      </CartItem>
                      <Total :goods="goods"></Total>
                   </div>`
    }

    // 整个应用的根组件
    const App = {
        components: {
            ShoppingCart
        },
        template: `<div class="wrapper">
                       <ShoppingCart :goods="goods"></ShoppingCart>
                       <button @click="add">添加新商品</button>
                   </div>`,
        data() {
            return {
                goods: [
                    { id: 1234, name: 'Java从入门到放弃', price: 99, amount: 7 },
                    { id: 2233, name: 'Java从没入门到放弃', price: 88, amount: 4 },
                    { id: 4321, name: '骗你学Vue之你行你上啊', price: 56, amount: 1 },
                ]
            }
        },
        methods: {
            add() {
                let x = {
                    id: 5678,
                    name: '睡佛是怎样炼成的',
                    price: 108,
                    amount: 12
                }
                this.goods.push( x );
            }
        }
    }

    Vue.createApp(App).mount('#application');

})();